from pydantic import BaseModel, Field
from typing import List, Optional, Dict, Any, Generic, TypeVar
from datetime import datetime
from enum import Enum

T = TypeVar('T')

class APIResponse(BaseModel, Generic[T]):
    """统一API响应格式 - 简化版本"""
    success: bool = True
    message: str = "操作成功"
    data: Optional[T] = None
    timestamp: datetime = Field(default_factory=datetime.utcnow)

# 用户相关模型
class UserCreate(BaseModel):
    """用户创建模型 - 简化版本"""
    username: str = Field(..., min_length=3, max_length=50, description="用户名")
    email: str = Field(..., pattern=r'^[^@]+@[^@]+\.[^@]+$', description="邮箱")
    password: str = Field(..., min_length=6, description="密码")
    full_name: Optional[str] = Field(None, max_length=100, description="全名")

class UserLogin(BaseModel):
    """用户登录模型"""
    username: str = Field(..., description="用户名")
    password: str = Field(..., description="密码")

class UserInfo(BaseModel):
    """用户信息模型 - 简化版本"""
    id: str
    username: str
    email: str
    full_name: Optional[str] = None
    role: str = "user"
    is_active: bool = True
    created_at: datetime
    last_login: Optional[datetime] = None

# 任务相关模型
class TaskStatus(str, Enum):
    """任务状态"""
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELLED = "cancelled"

class SimpleTaskConfig(BaseModel):
    """简化的任务配置"""
    name: str = Field(..., description="任务名称")
    urls: List[str] = Field(..., description="要爬取的URL列表")
    description: Optional[str] = Field(None, description="任务描述")

class SimpleTaskInfo(BaseModel):
    """简化的任务信息"""
    id: str
    name: str
    urls: List[str]
    status: TaskStatus = TaskStatus.PENDING
    description: Optional[str] = None
    created_at: datetime
    updated_at: Optional[datetime] = None
    result: Optional[Dict[str, Any]] = None
    error_message: Optional[str] = None

class TaskCreateRequest(BaseModel):
    """任务创建请求"""
    config: SimpleTaskConfig
    execute_immediately: bool = Field(False, description="是否立即执行")

class TaskUpdateRequest(BaseModel):
    """任务更新请求"""
    config: SimpleTaskConfig

# 分页相关
class PaginatedResponse(BaseModel):
    """分页响应"""
    items: List[Any]
    total: int
    page: int
    size: int
    pages: int

class TaskListParams(BaseModel):
    """任务列表查询参数"""
    page: int = Field(1, ge=1, description="页码")
    size: int = Field(20, ge=1, le=100, description="每页数量")
    status: Optional[TaskStatus] = Field(None, description="状态过滤")
    search: Optional[str] = Field(None, description="关键词搜索")
